/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


function selectScore() {
    document.getElementById('GPA').style.display = 'none';
    document.getElementById('GPAA').style.display = 'none';
    document.getElementById('Ambition').style.display = 'none';
    document.getElementById('AmbitionResult').style.display = 'none';
	document.getElementById('Score').style.display = 'block';  
	document.getElementById('ScorePanel').style.display = 'block'; 
	document.getElementById('ScoreResult').style.display = 'block';   
}

function selectGPA() {
	document.getElementById('Score').style.display = 'none';
	document.getElementById('ScorePanel').style.display = 'none'; 
	document.getElementById('ScoreResult').style.display = 'none';
    document.getElementById('Ambition').style.display = 'none';
    document.getElementById('AmbitionResult').style.display = 'none';
    document.getElementById('GPA').style.display = 'block';
    document.getElementById('GPAA').style.display = 'block';
}

function selectAmbition() {
    document.getElementById('GPA').style.display = 'none';
    document.getElementById('GPAA').style.display = 'none';
	document.getElementById('Score').style.display = 'none';
	document.getElementById('ScorePanel').style.display = 'none'; 
	document.getElementById('ScoreResult').style.display = 'none';
    document.getElementById('Ambition').style.display = 'block';
    document.getElementById('AmbitionResult').style.display = 'block';
}

// Logic Defined Function
//New Defined Function

//common Function
//append jsonObject2 to last element of jsonObject1
function appendNewData (jsonObject1, jsonObject2){
    alert('call appendNewData( obj1, obj2)');
    //get object from local json storage
    json1 = JSON.parse(JSON.stringify(jsonObject1));
    json2 = JSON.parse(JSON.stringify(jsonObject2));
    
    // concate new json object
    json1 = json1.concat(json2);
    alert('get tempJName to setItem: '+sessionStorage.getItem('tempJName'));
    localStorage.setItem(sessionStorage.getItem('tempJName'), JSON.stringify(json1));
    alert('append');
}

//sample function to add new data
function addNewData(){
    alert('call addNewData()');
    // local storage
    jName = JSON.parse(localStorage.getItem('jName2'));
    // new item 
    jName2 ={'numeric1': "goud", 'numeric2':"1", 'numeric3': "7", "numeric4": "8"};
    
    //store temporary primary jName to tempJName
    sessionStorage.setItem('tempJName', 'jName2');
    alert('tempJName: '+sessionStorage.getItem('tempJName'));

    // call function appendNewData
    appendNewData(jName, jName2);
    alert('addNewData');
}

//load all local storage
 function displayStorage() {
	var num, out, i, key, value;
	if (window.localStorage) {
		num = window.localStorage.length;
		if (num > 0) {
			out = "<table width='900px' cellpadding='4px' border='1px'>";
			out += "<tr><td>Key</td><td>Value</td></tr>";
			for (i = 0; i < num; i = i + 1) {
				key = window.localStorage.key(i);
				value = window.localStorage.getItem(key);
				out += "<tr><td>" + key + "</td><td>" + value + "</td></td></tr>";
			}
			out += "</table>";
			setContent("localStorage", out);
		}
	} 
}
function setContent(id, content) {
	var ele = document.getElementById(id);
	if (ele) {
		ele.innerHTML = content;
	}
}

//Grades alphabet to number
function setDefaultContentGrade(){
    localStorage.setItem('A+', '4.3');
    localStorage.setItem('A', '4');
    localStorage.setItem('A-', '3.7');
    localStorage.setItem('B+', '3.5');
    localStorage.setItem('B', '3');
    localStorage.setItem('B-', '2.7');
    localStorage.setItem('C+', '2.5');
    localStorage.setItem('C', '2');
    localStorage.setItem('D', '1');
    localStorage.setItem('E', '0');
    localStorage.setItem('F', '');

    num = parseFloat(localStorage.getItem('B+'));
    alert('num = '+ num);
}
// JSON parsing get set gpaSemester semesterName --> Semester Recap
function getGPASemesterBySemesterName(json, semesterName){ 
        for (var i in json) {
            if (json[i].semesterName == semesterName) {
                return json[i].gpaSemester;
            }
        }
}
function setGPASemesterBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].gpaSemester = val;
            break;
        }
    }
    //return json; 
} 

// JSON parsing get set totalCredit semesterName --> Semester Recap
function getTotalCreditBySemesterName(json, semesterName){ 
        for (var i in json) {
            if (json[i].semesterName == semesterName) {
                return json[i].totalCredit;
            }
        }
}
function setTotalCreditBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].totalCredit = val;
            break;
        }
    }
    //return json; 
} 

// JSON parsing get set numberOfCourse semesterName --> Semester Recap
function getNumberOfCourseBySemesterName(json, semesterName){ 
        for (var i in json) {
            if (json[i].semesterName == semesterName) {
                return json[i].numberOfCourse;
            }
        }
}
function setNumberOfCourseBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].numberOfCourse = val;
            break;
        }
    }
    //return json; 
}

//Delete item on jSemesterRecap by SemesterName
function deleteItemBySemesterName(json, semesterName) {
    for(var i=0; i<json.length; i++) { 
        if(json[i].semesterName == semesterName) {
            json.splice(i,1);
            break;
        }
    } 
}

//==============================================================================
//GPA AMBITION
// initialization data newAmbition
function insertNewDataAmbition(){
    localStorage.setItem('jGPAAmbition', JSON.stringify([{
        currentGPA: '3.21',
        creditsCompleted: '100',
        wantedGPA: '3.5',
        creditsLeft: '44',
        ambitionResult: '3.78'
        }]));
    
    var ambitionRes = JSON.parse(localStorage.getItem('jGPAAmbition'));
    alert(ambitionRes[0].ambitionResult);
    var gpaResult = ambitionRes[0].ambitionResult;
    document.getElementById('gpaAmbitionResult').innerHTML = gpaResult;
}

// get GPA and credits from database
function retrieveCurrentGPACredits(){
    tempGPA = JSON.parse(localStorage.getItem('jGPAAmbition'));
    var currentGPA = tempGPA[0].currentGPA;
    var creditsCompleted = tempGPA[0].creditsCompleted;
    document.getElementById('inputCurrentGPA').value = currentGPA;
    document.getElementById('inputCreditsCompleted').value = creditsCompleted;
}

//calculate GPA Ambition
function calculateAmbition(){
    var cg = parseFloat(document.getElementById('inputCurrentGPA').value);
    var cc = parseFloat(document.getElementById('inputCreditsCompleted').value);
    var ag = parseFloat(document.getElementById('inputWantedGPA').value);
    var cl = parseFloat(document.getElementById('inputCreditsLeft').value);
    var gr = 0;
    alert(gr);
    alert (cg);
    alert (cc);
    alert (ag);
    alert (cl);
    if ((cg != null)&& (cc != null) &&(ag != null) && (cl != null)){
        //calculate and insert DOM element
        gr = (((cl + cc) * ag) - (cg * cc))/cl;
        alert ('gr :'+gr);
        document.getElementById('resultOpening').innerHTML = 'You need to achieve minimum GPA: ';
        document.getElementById('gpaAmbitionResult').innerHTML = parseFloat(gr.toFixed(2));
        document.getElementById('creditsLeft').innerHTML = 'for the '+cl+' credits left!';
        
        //save to local storage
        localStorage.setItem('jGPAAmbition', JSON.stringify([{
        currentGPA: cg,
        creditsCompleted: cc,
        wantedGPA: ag,
        creditsLeft: cl,
        ambitionResult: gr
        }]));
    }
}

//==============================================================================
// Add new course
function initializationNewSemesterRecap(){
    localStorage.setItem('jSemesterRecap', JSON.stringify([{
        semesterName: '2011-Spring',
        gpaSemester: '3.5',
        totalCredit: '100',
        numberOfCourse: '40'
        }]));
    /*
    var ambitionRes = JSON.parse(localStorage.getItem('jGPAAmbition'));
    alert(ambitionRes[0].ambitionResult);
    var gpaResult = ambitionRes[0].ambitionResult;
    document.getElementById('gpaAmbitionResult').innerHTML = gpaResult;
    */
}

function saveCourse(){
    var courseName = document.getElementById('inputCourseName').value;
    var credit = parseInt(document.getElementById('inputCredit').value);
    var year = document.getElementById('inputYear').value;
    var termOption = document.getElementById('inputTermOption').value;
    var grade = parseFloat(document.getElementById('inputGrade').value);
    var semesterName = year + "-"+termOption;
    
    //check existing semester name, get local storage index 
    var num, i, key;
    if (window.localStorage) {
        num = window.localStorage.length;
        alert ('num = '+num);
        if (num > 0) {
            for (i = 0; i < num; i = i + 1) {
                key = window.localStorage.key(i);
                if(key == semesterName){
                    alert('i = '+i);
                    break;
                }
            }
        }
    } 
    
    // new local storage
    if (i==num){
        //firt element
        localStorage.setItem(semesterName, JSON.stringify([{
            courseName: courseName,
            credit: credit,
            year: year,
            termOption: termOption,
            grade: grade
        }])); 
        alert ('insert First Element');
    }
    //
    else{
        //check existing element, if null, insert first element
        if (JSON.parse(localStorage.getItem(semesterName))[0].courseName == null){
            localStorage.setItem(semesterName, JSON.stringify([{
                courseName: courseName,
                credit: credit,
                year: year,
                termOption: termOption,
                grade: grade
            }])); 
            alert ('insert First Element');
        }
        //append new element
        else {
            // local storage
            jName = JSON.parse(localStorage.getItem(semesterName));
            // new item 
            jName2 ={courseName: courseName, credit: credit, year: year, termOption: termOption, grade: grade};

            //store temporary primary jName to tempJName
            sessionStorage.setItem('tempJName', semesterName);
            alert('tempJName: '+sessionStorage.getItem('tempJName'));

            // call function appendNewData
            appendNewData(jName, jName2);
            alert('addNewData');
        }
    }
    alert("Add Course Successful!");
    alert (JSON.parse(localStorage.getItem(semesterName))[0].courseName);
    alert (JSON.parse(localStorage.getItem(semesterName))[1].courseName);
}


function semesterRecapUpdate(semesterName, credit, grade){
    //check existing
    var json = JSON.parse(localStorage["jSemesterRecap"]);
    var gpaSemester = getGPASemesterBySemesterName(json, semesterName);
    
    //new data update didnt exist
    if (gpaSemester == null){
        //calculate GPA first
        gradeConvert = parseFloat(localStorage.getItem(grade));
        alert('grade Convert Result = '+ gradeConvert);
        
        // append new semester data
        //set numberOfCourse = 1
        
    }
}


function deleteCourse(){

    /*
    var parsed = JSON.parse(localStorage.getItem('2011-Spring'));
    alert("Object length = "+JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName);
    JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName = "TA-3";
    alert("Object length = "+JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName);
    */
    //localStorage.removeItem('semesterName');
    /*
    localStorage.setItem('jSemesterRecap', JSON.stringify([{
        semesterName: '2011-Spring',
        gpaSemester: '3.5',
        totalCredit: '100',
        numberOfCourse: '40'
        },
    {
        semesterName: '2012-Spring',
        gpaSemester: '3',
        totalCredit: '133',
        numberOfCourse: '13'
        }]));
    */
    
    //var json = JSON.parse(localStorage["jSemesterRecap"]);
    //var href = getItemHrefById(json, "2011-Spring");
   // alert('current GPA semester'+href);

    //update set jSemesterRecap gpaSemester 
    //setItemHrefById(json, '2011-Spring', '3.1');
    //var href = getItemHrefById(json, "2011-Spring");
    //alert('New Gpa Semester'+href);
      
   
    // update storage:
    //deleteItemById(json, '2011-Spring');
    //localStorage["jSemesterRecap"] = JSON.stringify(json);
    
    //var json = JSON.parse(localStorage["jSemesterRecap"]);
    //var href = getItemHrefById(json, "2011-Spring");
    //alert('current GPA semester'+href);
}


//==============================================================================
// Setting Page
function appendNewDataTest (){
    
    localStorage.setItem('jName', JSON.stringify([{
        numeric1: '44',
        numeric2: '2',
        numeric3: '3',
        numeric4: '4'
        },
    {
        numeric1: '134324',
        numeric2: '342',
        numeric3: '4324',
        numeric4: '23432'
        }
    ]      
    ));
    
    //set local storage from input user (new local storage)
    var jData = [{numeric1: '5', numeric2: '6', numeric3: '7', numeric4: '8'}];
    localStorage.setItem('jName2', JSON.stringify(jData));
    
    //get object from local json storage
    var json1Object = JSON.parse(localStorage.getItem('jName'));
    var json2Object = JSON.parse(localStorage.getItem('jName2'));
    
    //get String from local json storage
    var json1String = JSON.stringify(localStorage.getItem('jName'));
    var json2String = JSON.stringify(localStorage.getItem('jName2'));

    // access object from json
    alert(json1Object[1].numeric1);
    
    var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
    var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
    jsonArray1 = jsonArray1.concat(jsonArray2);
    alert (typeof jsonArray1);
    
    // concate new json object
    json1Object = json1Object.concat(json2Object);
    alert('type of jSon 1 Object: '+typeof json1Object);
    
    
    localStorage.setItem('jName3', JSON.stringify(json1Object));
    
    alert('append');
}



//functions for entering a password, setting a password, redirecting or denying access to the password setup screen, setting the secret question and answer, and reseting the password
function setPass() {
    if (mypass.value != null) {
	localStorage.setItem('password',mypass.value);
        alert (localStorage.getItem('password'));
    }
}
function changePassSetting() {
    if (passSet.value != null) {
        localStorage.setItem('passSet',passSet.value);
        alert (localStorage.getItem('passSet'));
    }
}
function checkPassSetting(){
    if(localStorage.getItem('passSet') == 'yes'){
        alert ('passSetting == yes');
        alert('Insert set password form');
    }
    else {
        alert ('passSetting unset');
        alert ('passSetting =='+localStorage.getItem('passSet'));
    }
}

//Setting Page
function storeDefaultValueTerm(){
    localStorage.setItem('jSettingTerm', JSON.stringify([{
        numeric1: '1',
        numeric2: '2',
        numeric3: '3',
        numeric4: '4',
        seasonal1: 'Spring',
        seasonal2: 'Summer',
        seasonal3: 'Autumn',
        seasonal4: 'Winter'
        }]
    )
    );
    alert('set default value term');    
    //alert (JSON.parse(localStorage.getItem('jSettingTerm')).numeric1);
}
function storeDefaultValueGrade(){
    localStorage.setItem('jGrade', JSON.stringify([{
        A: '4',
        AB: '3.5',
        B: '3',
        BC: '2.5',
        C: '2',
        D: '1',
        E: '0',
        F: null
        }])
    )
    alert('set default value grade');
}

//show all grade
function showAllGrade(){
    var out, i, key, value;
    out = "<table width='900px' cellpadding='4px' border='1px'>";
    out += "<tr><td>Key</td><td>Value</td></tr>";
    key = 'jGrade';
    value = window.localStorage.getItem(key);
    out += "<tr><td>" + key + "</td><td>" + value + "</td></td></tr>";
    out += "</table>";
    setContent("grade", out);
}

//
function showAllTerm(){
    var out, i, key, value;
    out = "<table width='900px' cellpadding='4px' border='1px'>";
    out += "<tr><td>Key</td><td>Value</td></tr>";
    key = 'jSettingTerm';
    value = window.localStorage.getItem(key);
    out += "<tr><td>" + key + "</td><td>" + value + "</td></td></tr>";
    out += "</table>";
    setContent("term", out);
}
   
    //numeric3: document.getElementById('JSONbox').value,
//accessing key properties
function jsonConcat(o1, o2) {
    for (var key in o2) {
    o1[key] = o2[key];
    }
    return o1;
}

